import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:orginone/dart/extension/index.dart';
import 'package:orginone/components/XImage/XImage.dart';
import 'package:orginone/components/XStatefulWidget/XStatefulWidget.dart';
import 'dart:ui' as ui;
import 'package:orginone/config/constant.dart';
import 'package:orginone/config/theme/space.dart';
import 'package:orginone/config/theme/unified_style.dart';
import 'package:orginone/dart/core/public/enums.dart';
import 'package:orginone/routers/pages.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qr_flutter/qr_flutter.dart';
import '../../../dart/base/schema.dart';
import '../../../main.dart';
import '../../../utils/system/PermissionUtil.dart';
import '../../BeautifulBGWidget/BeautifulBGWidget.dart';
import '../../Tip/ToastUtils.dart';
import '../../MessageForwardWidget/MessageForwardWidget.dart';
import '../../XText/XText.dart';

///实体二维码
class EntityQRCodeWidget extends XStatefulWidget<XEntity> {
  EntityQRCodeWidget({super.key});

  @override
  State<EntityQRCodeWidget> createState() => _EntityQRCodeState();
}

class _EntityQRCodeState extends XStatefulState<EntityQRCodeWidget, XEntity> {
  final GlobalKey globalKey = GlobalKey();
  late XEntity entity = XEntity(id: "", typeName: "");
  _EntityQRCodeState();

  @override
  void initState() {
    super.initState();
    entity = RoutePages.routeData.currPageData.data;
    // Future.delayed(Duration(seconds: 0), () async {
    //
    // });
  }

  @override
  Widget buildWidget(BuildContext context, XEntity entity) {
    return buildMainView();
  }

  Widget buildMainView() {
    return <Widget>[
      buildUserQrInfoView(),
      const Expanded(
        child: SizedBox(),
      ),
      buildActions().paddingBottom(16)
    ].toColumn();
  }

  Widget buildUserQrInfoView() {
    return Container(
      width: ScreenUtil().screenWidth,
      height: 450,
      padding: EdgeInsets.only(
          top: AppSpace.paragraph * 2,
          bottom: AppSpace.paragraph,
          left: AppSpace.paragraph,
          right: AppSpace.paragraph),
      child: RepaintBoundary(
          key: globalKey,
          child: BeautifulBGWidget(
              showBack: false,
              showLogo: false,
              body: <Widget>[
                infoView(),
                buildQRImageView().paddingTop(AppSpace.paragraph),
                buildTipTextView().paddingTop(AppSpace.card),
              ].toColumn().paddingAll(AppSpace.paragraph))),
    );
  }

  /// 用户信息相关
  Widget infoView() {
    var image = entity.avatarThumbnail();
    return <Widget>[
      // ImageWidget(image, size: 60.w, fit: BoxFit.fill, radius: 5.w)
      //     .paddingRight(AppSpace.listItem),
      XImage.entityIcon(entity, size: Size(60.w, 60.w), radius: 5.w)
          .paddingRight(AppSpace.listItem),
      <Widget>[
        XText.listTitle(
          entity.name,
          // style: AppTextStyles.titleMedium,
        ),
        XText.listSubTitle(
          entity.remark,
          // style: AppTextStyles.bodySmall,
          // maxLines: 1,
          // overflow: TextOverflow.ellipsis,
        ).width(300.w).paddingTop(AppSpace.button),
      ].toColumn(crossAxisAlignment: CrossAxisAlignment.start)
    ].toRow();
  }

  ///二维码
  Align buildQRImageView() {
    // var image = entity.avatarThumbnail();
    return Align(
      alignment: Alignment.center,
      child: QrImageView(
        data: '${Constant.host}/${entity.id}',
        version: QrVersions.auto,
        size: 260.w,
        // embeddedImage: image != null ? MemoryImage(image) : null,
        errorCorrectionLevel: QrErrorCorrectLevel.H,
        // embeddedImageStyle: QrEmbeddedImageStyle(size: Size(60.w, 60.w)),
        dataModuleStyle: const QrDataModuleStyle(
          dataModuleShape: QrDataModuleShape.square,
          color: Colors.black,
        ),
        eyeStyle: const QrEyeStyle(
          eyeShape: QrEyeShape.square,
          color: Colors.black,
        ),
      ),
    );
  }

  ///提示语
  Widget buildTipTextView() {
    return XText.tip(
      getRemarkData(),
    );
  }

  Widget buildActions() {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          buildButton(
              iconData: Icons.download_sharp,
              title: '保存到相册',
              onTap: () => save(),
              txtColor: Colors.white,
              color: XColors.primary),
          buildButton(
              iconData: Icons.share_sharp,
              title: '分享',
              onTap: () => share(),
              txtColor: Colors.black,
              color: XColors.white),
        ],
      ),
    );
  }

  buildButton(
      {required String title,
      required IconData iconData,
      required Color color,
      required Color txtColor,
      required Function onTap}) {
    return <Widget>[
      Container(
        width: (ScreenUtil().screenWidth - 40) / 2,
        height: 40,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: color,
          borderRadius: BorderRadius.circular(6),
        ),
        child: XText.buttonSolid(title, color: txtColor
            // style: TextStyle(
            //   color: txtColor,
            //   fontSize: 16,
            //   fontFamily: 'PingFang SC',
            //   fontWeight: FontWeight.w600,
            // ),
            ),
      )
    ].toColumn().onTap(() => onTap());
  }

  String getTitleData() {
    return "${entity.typeName}二维码";
  }

  String getRemarkData() {
    return entity.typeName == null
        ? "'扫一扫上面的二维码图案，一起分享吧'"
        : entity.typeName == TargetType.person.label
            ? "打开奥集能App扫描二维码,申请添加好友"
            : "打开奥集能App扫描二维码,申请加入${entity.typeName}";
  }

  scan() {
    // Log.info('扫描');
    // IndexController c = Get.find<IndexController>();
    // c.qrScan();
    relationCtrl.qrScan(context);
  }

  share() async {
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return MessageForwardWidget(
            msgBody: jsonEncode(entity.toJson()),
            msgType: MessageType.card.label,
            onSuccess: () {
              Navigator.pop(context);
            },
          );
        },
        isScrollControlled: true,
        isDismissible: false,
        useSafeArea: true,
        barrierColor: Colors.white);
    return;
    // RenderRepaintBoundary boundary =
    //     globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    // ui.Image image = await boundary.toImage(pixelRatio: 2.0);
    // ByteData? byteData =
    //     await (image.toByteData(format: ui.ImageByteFormat.png));

    // if (byteData != null) {
    //   // 将 ByteData 转换为 Uint8List
    //   final uint8List = byteData.buffer.asUint8List();
    //   var file = await saveImage(uint8List);
    //   var docDir = relationCtrl.user?.directory;
    //   var item = await docDir?.createFile(
    //     File(file.path),
    //     p: (progress) {},
    //   );

    //   if (item != null) {
    //     showModalBottomSheet(
    //         context: navigatorKey.currentState!.context,
    //         builder: (context) {
    //           return MessageForward(
    //             msgBody: jsonEncode(item.shareInfo().toJson()),
    //             msgType: MessageType.image.label,
    //             onSuccess: () {
    //               Navigator.pop(context);
    //             },
    //           );
    //         },
    //         isScrollControlled: true,
    //         isDismissible: false,
    //         useSafeArea: true,
    //         barrierColor: Colors.white);
    //   }
    // }
  }

  save() async {
    // Log.info('保存');
    await PermissionUtil.showPermissionDialog(context, Permission.storage,
        callback: () async {
          saveAssetsImg();
        });
  }

  // 动态申请权限，ios 要在info.plist 上面添加
  // / 动态申请权限，需要区分android和ios，很多时候它两配置权限时各自的名称不同
  // / 此处以保存图片需要的配置为例
  Future<bool> requestPermission() async {
    // 1、读取系统权限的弹框
    PermissionStatus storageStatus = await Permission.storage.status;
    if (storageStatus != PermissionStatus.granted) {
      if (Platform.isIOS) {
        storageStatus = await Permission.photosAddOnly.request();
      } else {
        storageStatus = await Permission.storage.request();
        // Log.info('storageStatus: $storageStatus');
        // storageStatus = await Permission.manageExternalStorage.request();
      }
    }

    // 2、假如你点not allow后，下次点击不会在出现系统权限的弹框（系统权限的弹框只会出现一次），
    // 这时候需要你自己写一个弹框，然后去打开app权限的页面
    if (storageStatus != PermissionStatus.granted) {
      showCupertinoDialog(
          context: context,
          builder: (context) {
            return CupertinoAlertDialog(
              title: const Text('需要给相册授权'),
              content: const Text('请到您的手机设置打开相册访问权限'),
              actions: <Widget>[
                CupertinoDialogAction(
                  child: const Text('取消'),
                  onPressed: () {
                    Navigator.pop(context);
                  },
                ),
                CupertinoDialogAction(
                  child: const Text('去设置'),
                  onPressed: () {
                    Navigator.pop(context);
                    // 打开手机上该app权限的页面
                    openAppSettings();
                  },
                ),
              ],
            );
          });
      return false;
    } else {
      return true;
    }
  }

// 保存APP里的图片
  saveAssetsImg() async {
    RenderRepaintBoundary boundary =
        globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    ui.Image image = await boundary.toImage(pixelRatio: 4.0);
    ByteData? byteData =
        await (image.toByteData(format: ui.ImageByteFormat.png));
    if (byteData != null) {
      final result =
          await ImageGallerySaver.saveImage(byteData.buffer.asUint8List());
      if (result['isSuccess']) {
        ToastUtils.showMsg(msg: "保存图片成功");
      } else {
        ToastUtils.showMsg(msg: "保存失败");
      }
    }
  }

  //将回调拿到的Uint8List格式的图片转换为File格式
  saveImage(Uint8List imageByte) async {
    //获取临时目录
    var tempDir = await getTemporaryDirectory();
    //生成file文件格式
    var file =
        await File('${tempDir.path}/image_${DateTime.now().millisecond}.jpg')
            .create();
    //转成file文件
    file.writeAsBytesSync(imageByte);
    return file;
  }
}
